package com.nulldev.util.internal.backport.httpclient_rw.testing;

import java.io.InputStream;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.internal.backport.httpclient_rw.httpclient.BackportedHttpRequest;
import com.nulldev.util.io.FastIO.FastIO;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpClient.HttpRequest;
import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpClient.ResponseFormat;

public class RWSpeedTest {

	public static void main(String[] args) throws Exception {
		final HttpRequest<InputStream> ris = new BackportedHttpRequest<InputStream>() {

			@Override
			public ResponseFormat getFormat() {
				return ResponseFormat.STREAM;
			}

		}.url("http://speedtest.tele2.net/10MB.zip").enableBuffering(16384);
		JVM.println("=> Testing throughput using a 10 MB test file.");
		final HttpResponse<InputStream> is = ris.create();
		final InputStream ois = is.data();
		int r = 0, read = 0;
		final long len = is.length();
		JVM.println("=> Content-Length: " + len);
		final byte[] data = new byte[16384];
		final long s = System.currentTimeMillis();
		while ((r = ois.read(data)) != -1 && read != len) {
			read += r;
			JVM.println("read: " + read + ", r: " + r);
		}
		final long e = System.currentTimeMillis();
		JVM.println("=> Downloaded.");
		is.close();
		JVM.println("=> Total read: " + read + " (" + FileUtil.convertToStringRepresentation(read) + ")");
		JVM.println("=> Time taken: " + (e - s) + " ms");
		FastIO.get().flush();
		JVM.exit();
	}

}
